package com.example.roam.game.leshan.view;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import androidx.annotation.NonNull;
import com.example.roam.game.leshan.control.GameFirstLsControl;

public class GameFirstLsUI extends SurfaceView implements SurfaceHolder.Callback {

    private GameFirstLsControl gameFirstLsControl;
    private SurfaceHolder surfaceHolder;

    public GameFirstLsUI(Context context) {
        super(context);
        initGame();
    }

    public GameFirstLsUI(Context context, AttributeSet attrs) {
        super(context, attrs);
        initGame();
    }

    public GameFirstLsUI(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initGame();
    }

    public void initGame(){
        surfaceHolder = this.getHolder();
        surfaceHolder.addCallback(this);
        gameFirstLsControl = new GameFirstLsControl(getContext());
    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        Runner runner = new Runner();
        runner.start();
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {

    }

    class Runner extends Thread{
        @Override
        public void run() {
            while (gameFirstLsControl.isVisible){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                draw();
            }
        }
    }

    public void draw(){
        Canvas canvas = surfaceHolder.lockCanvas();
        gameFirstLsControl.draw(canvas);
        surfaceHolder.unlockCanvasAndPost(canvas);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        gameFirstLsControl.onTouch(event);
        return true;
    }

    public GameFirstLsControl getGameFirstLsControl() {
        return gameFirstLsControl;
    }
}
